package logger

import (
	"crawlies/src/util/fileutil"
	"io"
	"log"
	"os"
	"time"
)

// Factory LoggerFactory 注意此处非入口
type Factory struct {
	outFile bool
	path    string
}

// NewLoggerFactory 建议全局创建后获取logger保存
func NewLoggerFactory(outFile bool, path string) *Factory {
	return &Factory{outFile: outFile, path: path}
}

func (l *Factory) GetLogger() *Logger {
	var out io.Writer
	if l.outFile {
		if l.path == "" {
			//获取路径
			wd, err := os.Getwd()
			if err != nil {
				log.Fatalln("get work directory failed", err.Error())
			}
			//拼接路径
			path := wd + "/log"
			//创建文件夹
			err2 := fileutil.Mkdir(path)
			if err2 != nil {
				log.Fatalln("make directory failed", err2.Error())
			}
			//创建文件
			logName := "/default" + time.Now().Format("20060102150405") + ".log"
			l.path = path + logName
			_, err3 := fileutil.MkFile(l.path)
			if err3 != nil {
				log.Fatalln("make file failed", err3.Error())
			}
		}
		file, err := os.OpenFile(l.path, os.O_CREATE|os.O_RDWR|os.O_APPEND, os.ModeAppend|os.ModePerm)
		if err != nil {
			log.Fatal(err, " logger initialize failed | cause log file can not open | path : "+l.path)
		}
		out = file
	} else {
		out = os.Stdout
	}
	debug := log.New(out, "[DEBUG] ", log.LstdFlags)
	info := log.New(out, "[INFO]  ", log.LstdFlags)
	errL := log.New(out, "[ERROR] ", log.LstdFlags)
	return &Logger{debug, info, errL}
}

type Logger struct {
	debug *log.Logger
	info  *log.Logger
	err   *log.Logger
}

func (l *Logger) Debug() *log.Logger {
	return l.debug
}

func (l *Logger) Info() *log.Logger {
	return l.info
}

func (l *Logger) Err() *log.Logger {
	return l.err
}
